package com.catering.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.catering.entity.UserAddress;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.catering.mapper.UserAddressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import com.alibaba.fastjson.JSONObject;

@Service
public class UserAddressService extends ServiceImpl<UserAddressMapper, UserAddress> implements IService<UserAddress> {
    
    @Autowired
    private AMapService amapService;
    
    /**
     * 保存用户地址
     * @param address 地址信息
     * @return 是否保存成功
     */
    @Transactional
    public boolean saveAddress(UserAddress address) {
        // 获取详细地址信息
        JSONObject addressInfo = amapService.getAddressByLocation(
            address.getLongitude(), address.getLatitude());
            
        if (addressInfo != null) {
            JSONObject addressComponent = addressInfo.getJSONObject("addressComponent");
            
            // 设置地址详细信息
            address.setProvince(addressComponent.getString("province"));
            address.setCity(addressComponent.getString("city"));
            address.setDistrict(addressComponent.getString("district"));
            address.setStreet(addressComponent.getString("street"));
            address.setStreetNumber(addressComponent.getString("streetNumber"));
            address.setBuilding(addressComponent.getString("building"));
            
            // 设置完整地址
            address.setAddress(addressInfo.getString("formatted_address"));
        }
        
        // 设置时间
        address.setCreateTime(new Date());
        address.setUpdateTime(new Date());
        
        // 如果是默认地址，将其他地址设为非默认
        if (address.getIsDefault()) {
            this.lambdaUpdate()
                .eq(UserAddress::getUserId, address.getUserId())
                .set(UserAddress::getIsDefault, false)
                .update();
        }
        
        return this.save(address);
    }
} 